#!/usr/bin/env python
import orange
import sys
from os import path

# -----------------------------------------------------------------------------
# -- Script for discretizing continuous data into discrete data.
# -- Requires an Orange formatted data file.
# -- See: http://www.ailab.si/orange/doc/reference/tabdelimited.htm
# -----------------------------------------------------------------------------

def usage():
  print "Usage:";
  print "python discretize.py [absolute path to Orange data file]";

# Hardcoded number of states.
bins = 3;

# Did we get cline arguments?
if len(sys.argv) < 2:
  usage();
  sys.exit(1);

# Retrieve input file from command line. 
inputFile = sys.argv[1];
inputFileName = path.splitext(inputFile)[0];
inputFileExt = path.splitext(inputFile)[1];
outputFile = (inputFileName + "_disc") + inputFileExt;

# Test for sanity of parameters. 
if ((inputFile == "") or (path.isfile(inputFile) == False)):
  print "Invalid input file.\n";
  print "";
  usage();
  sys.exit(1);

# Read in data. 
data = orange.ExampleTable(inputFile);

# Discretize. 
data_disc = orange.Preprocessor_discretize(data,method=orange.EquiNDiscretization(numberOfIntervals=bins));

# Rename states. 
for i in xrange(0,len(data.domain)):
  # If the variable was discrete in the original data, we don't need to
  # mess with renaming its states here. 
  if not data.domain[i].varType == 1:
    data_disc.domain[i].values = [str(s) for s in xrange(bins)];
  
# Rename variables.
for i in xrange(0,len(data.domain)):
  data_disc.domain[i].name = data.domain[i].name;

# Write out the discretized data. 
data_disc.save(outputFile);